import { 
    reactive, 
    toRefs, 
    defineComponent,
    ref,
    watch,
    onMounted, 
    nextTick,
    computed
} from 'vue';
import solarLunar from './utils/solarLunar.js';
// import solarLunar from 'solarlunar-es';
import nextDay from './utils/nextDay.js';
import lastDay from './utils/lastDay.js';
import {
    LUNAR_FESTIVAL,
    FESTIVAL,
    ARRANGE_HOLIDAY,
    WORKING_DAYS
} from './utils/lunarFestival.js';
import { getDayTaboo } from './utils/Almanac.js';
import { formatWeek } from '@/utils/util.js';
export default defineComponent({
    name:'xpCalendars',
    props: {

    },
    components: {

    },
    emits:[],
    setup (props, context) 
    {
        let data = reactive({
            selectYear:'',
            selectMonth:'',
            fullDateArray:[] as any,
            selectDayDate:'',
            dayInfo:{} as any,
            checkedDate:'',
            dayTaboo:[] as any
        });
        let methods = {
            initDate ()
            {
                let year = data.selectYear;
                let month = Number(data.selectMonth);
                let day = 1;
                let dayArr = [] as any;
                const DAY_LENTH = 42;
                let itemDay = [year, month, day].join('-');
                console.log(itemDay);
                
                let startDay = new Date(itemDay);
                let week = startDay.getDay();
                week = week === 0 ? 7 : week;
                for (let i = 1; i < week; i++) 
                {
                    itemDay = lastDay(new Date(itemDay));
                    let { term, dayCn, monthCn, cDay, cMonth, cYear } = solarLunar.solar2lunar(
                        ...itemDay.split('-')
                    );
                    if (FESTIVAL[cMonth] && FESTIVAL[cMonth][cDay]) 
                    {
                        term = FESTIVAL[cMonth][cDay];
                    }
                
                    if (LUNAR_FESTIVAL[monthCn] && LUNAR_FESTIVAL[monthCn][dayCn]) 
                    {
                        term = LUNAR_FESTIVAL[monthCn][dayCn];
                    }
                    let isWorkDay, isRestDay;
                    if (
                        WORKING_DAYS[cYear] &&
                      WORKING_DAYS[cYear][cMonth]
                    ) 
                    {
                        let range = WORKING_DAYS[cYear][cMonth];
                        if (range.includes(cDay)) isWorkDay = true;
                    }
                
                    if (ARRANGE_HOLIDAY[cYear] && ARRANGE_HOLIDAY[cYear][cMonth]) 
                    {
                        let range = ARRANGE_HOLIDAY[cYear][cMonth];
                        // if (cDay >= range[0] && cDay <= range[1]) isRestDay = true;
                        if (range.includes(cDay)) isRestDay = true;
                    }
                
                    dayArr.push({
                        day: itemDay.split('-')[2],
                        date: formatTime.value(itemDay),
                        d_day: term || dayCn,
                        isSelectClass: data.checkedDate === itemDay,
                        otherMonth: true,
                        hasTerm: term,
                        isWeekend:
                            (new Date(itemDay).getDay() === 6 || new Date(itemDay).getDay() === 0) &&
                            !isWorkDay,
                        isWorkDay: isWorkDay,
                        isRestDay: isRestDay
                    });
                }
                itemDay = [year, month, day].join('-');
                dayArr = dayArr.reverse();
                for (let i = 0; i <= DAY_LENTH - week; i++) 
                {
                    let { term, dayCn, monthCn, cMonth, cDay, cYear } = solarLunar.solar2lunar(
                        ...itemDay.split('-')
                    );
                    if (FESTIVAL[cMonth] && FESTIVAL[cMonth][cDay]) 
                    {
                        term = FESTIVAL[cMonth][cDay];
                    }
                    if (LUNAR_FESTIVAL[monthCn] && LUNAR_FESTIVAL[monthCn][dayCn]) 
                    {
                        term = LUNAR_FESTIVAL[monthCn][dayCn];
                    }
                    let isWorkDay, isRestDay;
                    if (
                        WORKING_DAYS[cYear] &&
                    WORKING_DAYS[cYear][cMonth]
                    ) 
                    {
                        let range = WORKING_DAYS[cYear][cMonth];
                        if (range.includes(cDay)) isWorkDay = true;
                    }

                    if (ARRANGE_HOLIDAY[cYear] && ARRANGE_HOLIDAY[cYear][cMonth]) 
                    {
                        let range = ARRANGE_HOLIDAY[cYear][cMonth];
                        // if (cDay >= range[0] && cDay <= range[1]) isRestDay = true;
                        if (range.includes(cDay)) isRestDay = true;
                    }
                    dayArr.push({
                        date: formatTime.value(itemDay),
                        day: itemDay.split('-')[2],
                        d_day: term || dayCn,
                        isSelectClass: data.checkedDate === itemDay,
                        otherMonth: Number(itemDay.split('-')[1]) !== month,
                        hasTerm: term,
                        isWeekend:
                            (new Date(itemDay).getDay() === 6 || new Date(itemDay).getDay() === 0) &&
                            !isWorkDay,
                        isWorkDay: isWorkDay,
                        isRestDay: isRestDay
                    });
                    itemDay = nextDay(new Date(itemDay));
                }
                //   清空原来的数据
                data.fullDateArray = [];
                for (let i = 0; i <= 5; i++) 
                {
                    data.fullDateArray.push(dayArr.splice(0, 7));
                }
            },
            getToday ()
            {
                let date = new Date();
                let year = date.getFullYear();
                let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
                let day = date.getDate();
                let week = date.getDay();
                data.selectDayDate = [year, month, day].join('-') + ' ' + formatWeek(week);
                data.selectYear = year.toString();
                data.selectMonth = month.toString();
                data.checkedDate = [year, month, day].join('-');
                data.dayInfo = solarLunar.solar2lunar(
                    year,
                    date.getMonth() + 1,
                    day
                );
                data.dayTaboo = getDayTaboo(data.dayInfo.gzDay);
                console.log(data.dayTaboo);
                
            },
            selectDayAction (e)
            {
                const date = e.target.getAttribute('date') || e.target.parentNode.getAttribute('date') ;
                let dateArr = date.split('-');
                let time  = new Date(dateArr.join('/'));
                data.selectDayDate = date + ' ' + formatWeek(time.getDay());
                data.checkedDate = date;
            },
            handleChangeYear (value)
            {
                data.selectMonth = '01';
                let date  = new Date([value, data.selectMonth, '01'].join('/'));
                data.selectDayDate = [value, data.selectMonth, '01'].join('-') + ' ' +  formatWeek(date.getDay());
                nextTick(methods.initDate);
            },
            handleChangeMonth (value)
            {
                let date  = new Date([data.selectYear, value, '01'].join('/'));
                data.selectDayDate = [data.selectYear, value, '01'].join('-') + ' ' +  formatWeek(date.getDay());
                nextTick(methods.initDate);
            },
            handlePrevMonth ()
            {
                let prev = Number(data.selectMonth) - 1;
                if (prev <= 0)
                {
                    data.selectMonth = '12';
                    data.selectYear = (Number(data.selectYear) - 1).toString();
                    let date  = new Date([data.selectYear, data.selectMonth, '01'].join('/'));
                    data.selectDayDate = [data.selectYear, data.selectMonth, '01'].join('-') + ' ' +  formatWeek(date.getDay());
                    nextTick(methods.initDate);
                    return;
                }
                data.selectMonth = prev < 10 ? `0${prev}` : prev.toString();
                methods.handleChangeMonth(data.selectMonth);
            },
            handleNextMonth ()
            {
                let next = Number(data.selectMonth) + 1;
                if (next > 12)
                {
                    data.selectMonth = '01';
                    data.selectYear = (Number(data.selectYear) + 1).toString();
                    let date  = new Date([data.selectYear, data.selectMonth, '01'].join('/'));
                    data.selectDayDate = [data.selectYear, data.selectMonth, '01'].join('-') + ' ' +  formatWeek(date.getDay());
                    nextTick(methods.initDate);
                    return;
                }
                data.selectMonth = next < 10 ? `0${next}` : next.toString();
                methods.handleChangeMonth(data.selectMonth);
            }
        };

        const formatTime = computed(() => 
        {
            return function (time)
            {
                let arr = time.split('-');
                arr[1] = Number(arr[1]) < 10 ? '0' + arr[1] : arr[1];
                arr[2] = Number(arr[2]) < 10 ? '0' + arr[2] : arr[2];
                return arr.join('-');
            };
        });

        watch(() => data.selectDayDate, (newValue) => 
        {
            if (newValue)
            {
                let date = newValue.split(' ')[0];
                data.selectYear = date.split('-')[0];
                data.selectMonth = date.split('-')[1];
                let info = solarLunar.solar2lunar(...date.split('-'));
                data.dayInfo = {
                    lunarFestival: LUNAR_FESTIVAL[info.monthCn] ? LUNAR_FESTIVAL[info.monthCn][info.dayCn] : undefined,
                    festival: FESTIVAL[info.cMonth] ? FESTIVAL[info.cMonth][info.cDay] : undefined,
                    ...info
                };
                data.checkedDate = date;
                data.dayTaboo = getDayTaboo(data.dayInfo.gzDay);
                // 触发事件;
                nextTick(methods.initDate);
            }
        });

        onMounted(() => 
        {
            methods.getToday();
            methods.initDate();   
        });
        return { 
            ...toRefs(data),
            ...methods
        };
    }
});